var audioplayUtil = require("../../../utils/audioplay.js")
var share = require("../../../utils/share.js")

var app = getApp();
var id = ""; //获取分类id  
var dataParm = {}; //封装请求数据 
var shareTickets = ""
var titlegro = "" //栏目标题、
var hongbaointerval
Page({
  /**
   * 页面的初始数据
   */
  data: {
    authbg: getApp().globalData.authImg,
    authtitle: getApp().globalData.source + "red_packet/title1.png",
    authbtn2: getApp().globalData.source + "red_packet/btn2.png",
    authdialog: getApp().globalData.source + "dialog/dialog.png",
    hidebanner: false,
    showhongbaoicon: false,
    showhongbao: false,
    hongbaodata: {},
    indicatorDots: false,
    vertical: false,
    autoplay: true,
    circular: true,
    interval: 5000,
    duration: 500,
    currentSwiper: 0,
    maxPage: 10, //每页显示最大行数
    startPoint: 1, //第几页
    totalPages: -1, //总共几页
    page: 1,
    imgUrls: [],
    classfilyDataListProgram: [],
    indexNumberProgram: null, //当前播放音频下标

    classfilyDataList: [],
    indexNumber: null, //当前播放音频下标

    showloading: true,
    showbottom: true,
    timer: '', //播放时间 播放时间统计
    currentPosition: 0, //选定音频的播放位置
    duration: 0, //选定音频的长度

    play: true,
    free: true,
    url: "",

    classifyBannerId: "", //分类中的bannerid埋点
    userIdss: "",
    classifyProgramId: "", //栏目id点击分类中的某个栏目跳转到详情播放页
    classifyProgramName: "", //栏目名称
    dingshihongbaoshow: false,
    dingshihongbao: getApp().globalData.source + "dialog/dingshihongbao.png",
  },

  checklogin: function() {
    if (wx.getStorageSync("userId") == "" || wx.getStorageSync("userId") == undefined) {
      if (wx.getStorageSync("authtype") == "0") {
        this.setData({
          showAuth: true,
          showAuth2: false
        })
      } else {
        this.setData({
          showAuth: false,
          showAuth2: true
        })
      }
      return true
    } else {
      this.setData({
        showAuth: false,
        showAuth2: false
      })
      return false
    }
  },

  closePopUp: function() {
    var that = this;
    this.setData({
      dingshihongbaoshow: !that.data.dingshihongbaoshow
    })
  },

  authbtn: function() {
    var vm = this
    wx.showLoading({
      title: "正在检查网络.."
    })
    this.setData({
      authbtn: true
    })
  },
  bindGetUserInfo: function(e) {
    getApp().authInfo(e);
  },
  swiperChange: function(e) {
    this.setData({
      currentSwiper: e.detail.current
    })
  },
  tobannerdetails: function(e) {
    var vm = this
    var index = e.currentTarget.dataset.index;
    let bnimg = vm.data.imgUrls[index];
    vm.setData({
      classifyBannerId: bnimg.cSrc, //分类中的bannerid埋点
      userIdss: wx.getStorageSync("userId")
    })
    if (bnimg.isH5 == 1) {
      //跳转原生详情页
      wx.navigateTo({
        url: "../../day_day_listen/details/details?id=" + bnimg.cSrc + "&season=" + 1,
        success: function() {},
        fail: function() {}
      })
    } else if (bnimg.isH5 == 0) {
      //跳转h5详情页
      wx.navigateTo({
        url: "../../webview/webview?url=" + bnimg.cSrc,
        success: function() {},
        fail: function() {}
      })
    } else {
      wx.navigateTo({
        url: bnimg.cSrc,
        success: function() {},
        fail: function() {}
      })
    }
  },

  jumptotal: function() {
    wx.navigateTo({
      url: '../../my/mydetail/mydetail',
    })

    this.setData({
      showhongbao: false,
      showhongbaoicon: false
    })
  },
  //检测该页面是否有红包显示
  checkhongbao: function() {
    var iphone = wx.getStorageSync("iPhone");
    if (iphone != "-1") {
      return
    }

    var vm = this
    var data = {
      "pageConfig": "栏目列表页",
      "userId": wx.getStorageSync("userId")
    }
    getApp().request(getApp().globalData.https + "hd/listen/classify/random",
      "post", data,
      function(res) {
        console.log("红包数据：" + JSON.stringify(res))
        //state=1时,显示红包就开始倒计时，隐藏掉红包入口
        if (res.code == 0) {
          if (res.data.state == 1) {
            var time = 15
            vm.setData({
              showhongbaoicon: true
            })
            if (!vm.data.isweb) {
              hongbaointerval = setInterval(function() {
                if (time <= 0) {
                  clearInterval(hongbaointerval)
                  vm.setData({
                    showhongbaoicon: false
                  })
                }
                time--;
              }, 1000)
              vm.setData({
                hongbaodata: res
              })
            }
          } else {
            vm.setData({
              showhongbaoicon: false
            })
          }
        }
      },
      function(res) {});
  },

  openhongbao: function() {
    this.setData({
      showhongbao: true
    })
    //领取红包
    var vm = this
    var data = {
      "userId": wx.getStorageSync("userId"),
      "state": 1,
      "tb": vm.data.hongbaodata.tb
    }
    this.setData({
      showhongbaoicon: false
    })
    getApp().request(getApp().globalData.https + "hd/listen/classify/random/savetb",
      "post", data,
      function(res) {},
      function(res) {});
  },

  closeredpockets: function() {
    this.setData({
      showhongbao: false,
    })
  },

  bottombar: function() {

  },

  share: function() {},

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    var channel = options.channel;
    if (channel != undefined) {
      wx.setStorageSync("channel", channel)
    }
    wx.showLoading({
      title: "加载中...."
    })
    //app.checkLogin();
    wx.showShareMenu({
      withShareTicket: true
    })
    var that = this;
    id = options.id;
    //每日资讯
    if (id == "44") {
      this.setData({
        hidebanner: true
      })
    }
    titlegro = options.classify
    that.setData({
      programId: id,
      titlegro: titlegro
    })
    wx.setNavigationBarTitle({ //更改标题栏显示
      title: titlegro
    })
    if (id == "-1") {
      this.getList();
    } else {
      this.getdata();
    }
    if (this.data.status === 1) {
      var that = this;
      audioplayUtil.playaudio(e, that)
    }

    var showhomeicon = options.showhomeicon == "fx" ? true : ""; //判断是分享页进入还是小程序正常进入
    if (showhomeicon) {
      this.setData({
        showhomeicon: showhomeicon
      })
    }
    this.getbanner()
  },

  getbanner: function() {
    var that = this;
    //加载首页banner数据
    console.log(that.data.programId)
    var data = {
      "categoryId": that.data.programId,
      "type": "1",
      "platform": wx.getStorageSync("platform")
    }
    getApp().requestLoading(getApp().globalData.https + "programResource/commonBannerList",
      "get", data, "加载中...",
      function(res) {
        if (res.code == 0) {
          // 获取系统信息 

          that.setData({
            imgUrls: res.data,
            hidebanner: res.data.length == 0
          });
        }
      },
      function(res) {
        console.log(res)
      }
    )
  },


  getdata: function() {
    var that = this;
    if (wx.getStorageSync("userId") == undefined || wx.getStorageSync("userId") == '') {
      dataParm = {
        categoryId: id,
        startPoint: that.data.page,
        maxPage: that.data.maxPage,
      }
    } else {
      dataParm = {
        categoryId: id,
        startPoint: that.data.page,
        maxPage: that.data.maxPage,
        userId: wx.getStorageSync("userId")
      }
    }
    var url = "programResource/program/" + id
    that.setData({
      url: url
    })
    that.getDataList(url, dataParm);
  },

  /**
   * 播放音频
   */
  play: function(e) {
    if (this.checklogin()) return
    var that = this;
    let audioList = this.data.classfilyDataListProgram
    var indexNumbers = e.currentTarget.dataset.indexnumber; //当前操作对象的 index
    // 是否启用h5 
    let adl = audioList[indexNumbers]
    var id = adl.id;
    var season = e.currentTarget.dataset.season;
    var h5Url = adl.h5Url;
    if (adl.useH5 != 1) {
      //跳转页面，使用h5
      wx.navigateTo({
        url: "../../day_day_listen/details/details?id=" + id + "&season=" + season,
        success: function() {},
        fail: function() {}
      })
    } else {
      audioplayUtil.stopaudio(e, that)
      var id = e.currentTarget.dataset.id
      var programid = wx.getStorageSync("programid");
      if (id != programid) {
        that.setData({
          currentPosition: '00:00',
          duration: "00:00",
          sliderValue: 0,
        })
      }
      var indexNumberProgram = e.currentTarget.dataset.indexnumber;
      var indexNumber = e.currentTarget.dataset.season - 1;
      that.setData({
        indexNumberProgram: indexNumberProgram,
        indexNumber: indexNumber,
        pause: true, //暂停
        play: false, //播放
        classifyProgramId: id, //栏目id点击分类中的某个栏目跳转到详情播放页
        classifyProgramName: adl.title, //栏目名称
        userIdss: wx.getStorageSync("userId")
      })
      //根据栏目id查询栏目
      var data = {
        startPoint: 1,
        maxPage: 10
      }
      if (id != programid) {
        that.setData({
          page: 1
        })
      }
      audioplayUtil.getProgramCurrentSeason(id, data, that);
    }
  },

  /**
   * 监听button暂停按钮
   */
  stop: function(e) {
    var that = this;
    audioplayUtil.stopaudio(e, that);
    that.setData({
      pause: false, //暂停
      play: true, //播放
      indexNumberProgram: -1
    })
  },

  /**
   * 播放进度条手动调整
   */
  bindSliderchange: function(e) {
    var that = this;
    audioplayUtil.bindSliderchange(e, that)
  },


  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    if (wx.getStorageSync("userId") == "" || wx.getStorageSync("userId") == undefined) {
      if (wx.getStorageSync("tourist") != "1") {
        if (wx.getStorageSync("authtype") == "0") {
          this.setData({
            showAuth: true,
            showAuth2: false
          })
        } else {
          this.setData({
            showAuth: false,
            showAuth2: true
          })
        }
        return
      }
    } else {
      this.setData({
        showAuth: false,
        showAuth2: false
      })
    }
    wx.hideLoading()
    this.checkhongbao();
  },

  /**
   * 获取必听精选数据列表
   */
  getList: function() {
    var that = this;
    var dataParm;
    if (wx.getStorageSync("userId") == undefined || wx.getStorageSync("userId") == '') {
      dataParm = {
        startPoint: that.data.page,
        maxPage: that.data.maxPage,
      }
    } else {
      dataParm = {
        startPoint: that.data.page,
        maxPage: that.data.maxPage,
        userId: usersIds
      }
    }

    getApp().requestLoading(getApp().globalData.https + "programResource/chargeProgram/" + usersIds,
      "get", dataParm, "加载中...",
      function(res) {
        wx.stopPullDownRefresh()
        if (res.code == 0) {
          var dt = res.data;
          console.log(dt)
          if (res.data.data.length > 0) {
            // 获取系统信息  
            that.setData({
              classfilyDataListProgram: that.data.classfilyDataListProgram.concat(res.data.data),
              totalPages: dt.totalPages
            });
          } else {
            wx.showToast({
              title: res.message,
              icon: 'none',
              duration: 3000
            })
          }
        } else {
          wx.showToast({
            title: res.message,
            icon: 'none',
            duration: 3000
          })
        }

        that.setData({
          showloading: false
        })
      }
    )
  },
  /**
   * 获取栏目数据列表
   */
  getDataList: function(url, dataParm) {
    var that = this;
    app.request(app.globalData.https + url,
      "get", dataParm,
      function(res) {
        wx.stopPullDownRefresh()
        if (res.code == 0) {
          var dt = res.data;
          console.log(dt)
          if (res.data.data.length > 0) {
            // 获取系统信息  
            that.setData({
              classfilyDataListProgram: that.data.classfilyDataListProgram.concat(res.data.data),
              totalPages: dt.totalPages
            });
          } else {
            wx.showToast({
              title: res.message,
              icon: 'none',
              duration: 3000
            })
          }
        } else {
          wx.showToast({
            title: res.message,
            icon: 'none',
            duration: 3000
          })
        }

        that.setData({
          showloading: false
        })
      }
    )
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {
    var that = this;
    var url = that.data.url;
    this.setData({
      page: 1,
      classfilyDataListProgram: []
    })
    if (id == "-1") {
      this.getList()
    } else {
      this.getdata();
    }
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {
    var that = this;
    var url = that.data.url;
    if (that.data.totalPages == -1) {
      that.setData({
        showbottom: false
      })
      return
    }
    if (that.data.page < that.data.totalPages) {
      that.setData({
        bottomtext: '正在加载中...',
        page: that.data.page + 1
      })
      if (id == "-1") {
        that.getList()
      } else {
        that.getdata();
      }
    } else {
      that.setData({
        bottomtext: '没有更多内容了'
      })
    }
  },


  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function(e) {
    var that = this;
    var userIds = wx.getStorageSync("userId")
    if (e.from === 'button') {
      // 来自页面内转发按钮 
      var id = e.target.dataset.id
      var imageUrl = e.target.dataset.img
      var free = e.target.dataset.free
      var title = e.target.dataset.title
      console.log("是否免费" + free)
      if (free) {
        if (shareStatus == 0) {
          var data = {
            programId: id,
            title: title,
            imageUrl: encodeURI(imageUrl),
            path: "/pages/my/my_share/sharing_details/sharing_details"
          }
          return {
            title: wx.getStorageSync("userInfo").nickName + '邀您一起听' + title,
            path: data.path + "?userIds=" + userIds + "&id=" + id + "&showhomeicon=fx",
            imageUrl: data.imageUrl,
            success(res) {
              console.log("success")
              //分享成功
              console.log("进入个人。。。。。。。。。。。。。。")
              //分装提交数据 shareSource 栏目id shareStatus分享状态
              var datas = {
                userId: wx.getStorageSync("userId"),
                programId: id,
                shareSource: "0",
              }
              console.log(datas)
              that.singleGroupId(datas); //调取保存用户分享的栏目
            },
            fail(e) {
              console.log("fail")
            },
            //分享完成
            complete() {
              console.log("complete")
            }
          }
        } else {
          var data = {
            programId: id,
            title: title,
            imageUrl: encodeURI(imageUrl),
            path: "/pages/my/my_share/sharing_details/sharing_details"
          }
          return {
            title: wx.getStorageSync("userInfo").nickName + '邀您一起听' + title,
            success(res) {
              console.log("success")
              //分享成功
              console.log("进入个人。。。。。。。。。。。。。。")
              //分装提交数据 shareSource 栏目id shareStatus分享状态
              var datas = {
                userId: wx.getStorageSync("userId"),
                programId: id,
                shareSource: "0",
              }
              console.log(datas)
              that.singleGroupId(datas); //调取保存用户分享的栏目
            },
            fail(e) {
              console.log("fail")
            },
            //分享完成
            complete() {
              console.log("complete")
            }
          }
        }
      } else {
        var imageUrl = e.target.dataset.img
        return {
          imageUrl: encodeURI(imageUrl),
          title: wx.getStorageSync("userInfo").nickName + '邀您一起听' + titlegro,
          path: "/pages/home/classify/classify" + "?userIds=" + userIds + "&id=" + that.data.programId + "&classify=" + that.data.titlegro + "&showhomeicon=fx",
          success(res) {
            //分享成功
            console.log("进入右上角..分享")
          },
          fail(e) {},
          //分享完成
          complete() {}
        }
      }
    } else {
      var imageUrl = getApp().globalData.shareurl
      return {
        imageUrl: imageUrl,
        title: wx.getStorageSync("userInfo").nickName + '邀您一起听' + titlegro,
        path: "/pages/home/classify/classify" + "?userIds=" + userIds + "&id=" + that.data.programId + "&classify=" + that.data.titlegro + "&showhomeicon=fx",
        success(res) {
          console.log("success")
          //分享成功
          console.log("进入右上角..分享")
        },
        fail(e) {
          console.log("fail")
        },
        //分享完成
        complete() {
          console.log("complete")
        }
      }
    }
  },

  getGroupID: function(datas) { //获取分享群id
    wx.getShareInfo({
      shareTicket: shareTickets[0],
      success: function(res) {
        var encryptedData = res.encryptedData;
        var iv = res.iv;
        wx.login({
          success: function(res) {
            var code = res.code;
            console.log(code)
            var userId = datas.userId;
            var programId = datas.programId;
            var shareSource = datas.shareSource;
            var shareStatus = datas.shareStatus;
            var survivalTime = datas.survivalTime;
            var data = {
              'wxEncryptedData': encryptedData,
              "wxIv": iv,
              "userId": userId,
              "programId": programId,
              "shareSource": shareSource,
              "wxCode": code
            };
            console.log(data)
            //处理获取分享群信息
            app.request(app.globalData.https + "programResource/myProgramShare",
              "post", data,
              function(res) {
                console.log(res)
              },
              function(res) {
                console.log(res)
              }
            )
          }
        })
      }
    })
  },



  /**
   * 个人用户分享保存服务器方法调用
   */
  singleGroupId: function(data) {
    console.log("个人分享。。。。。。")
    app.request(app.globalData.https + "programResource/myProgramShare", //处理获取分享群信息
      "post", data,
      function(res) {
        if (res.code == 0) {
          console.log("调用接口" + res)
          console.log(res)
        }
      },
      function(res) {
        console.log(res)
      }
    )
  },


  /**
   * 跳转到播放详情页面
   */
  todetails: function(e) {
    let audioList = this.data.classfilyDataListProgram
    var indexNumbers = e.currentTarget.dataset.index; //当前操作对象的 index
    var season = e.currentTarget.dataset.season;
    let adl = audioList[indexNumbers];
    let id = adl.id
    // 是否启用h5 
    var h5Url = adl.h5Url;
    this.setData({
      playBthidShow: "play"
    })
    var vm = this
    vm.setData({
      play: true,
      pause: false,
      indexNumberProgram: -1,
      classifyProgramId: id, //栏目id点击分类中的某个栏目跳转到详情播放页
      classifyProgramName: adl.title, //栏目名称
      userIdss: wx.getStorageSync("userId")
    })
    wx.navigateTo({
      url: "../../day_day_listen/details/details?id=" + id + "&season=" + season,
      success: function() {},
      fail: function() {}
    })
  },

  search: function() {
    wx.navigateTo({
      url: "../../search/search",
      success: function() {},
      fail: function() {}
    })
  },
  // 回到首页
  gohome: function() {
    wx.switchTab({
      url: '/pages/style/style',
    })
  },
})